package com.bw.goods.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bw.common.vo.ShopSeckillVo;
import org.apache.commons.lang3.BooleanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bw.common.utils.PageUtils;
import com.bw.common.utils.Query;

import com.bw.goods.dao.GoodsDao;
import com.bw.goods.entity.GoodsEntity;
import com.bw.goods.service.GoodsService;


@Service("goodsService")
public class GoodsServiceImpl extends ServiceImpl<GoodsDao, GoodsEntity> implements GoodsService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String goodsList = redisTemplate.opsForValue().get("goodsList");
        if (goodsList != null) {
            // 缓存有数据
            System.out.println("缓存命中(商品列表)");
            return JSON.parseObject(goodsList,new TypeReference<PageUtils>(){});
        } else {
            // 占坑
            String uuid = UUID.randomUUID().toString().replace("-", "");
            Boolean lock = redisTemplate.opsForValue().setIfAbsent("goodsLock", uuid, 30, TimeUnit.SECONDS);
            if (BooleanUtils.isTrue(lock)) {
                try {
                    // 查询数据库
                    System.out.println("查询数据库(秒杀活动列表)");
                    IPage<GoodsEntity> page = this.page(
                            new Query<GoodsEntity>().getPage(params),
                            new QueryWrapper<GoodsEntity>()
                    );

                    PageUtils pageUtils = new PageUtils(page);
                    // 放入缓存
                    redisTemplate.opsForValue().set("goodsList", JSON.toJSONString(pageUtils));
                    return pageUtils;
                } finally {
                    // 删除锁
                    String script = "if redis.call(\"get\",KEYS[1]) == ARGV[1]\n" +
                            "then\n" +
                            "    return redis.call(\"del\",KEYS[1])\n" +
                            "else\n" +
                            "    return 0\n" +
                            "end";
                    redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList("goodsLock"), uuid);
                }
            } else {
                System.out.println("占坑失败(秒杀活动列表)");
                // 占坑失败 自旋等待100ms 调用方法本身
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return queryPage(params);
            }
        }
    }

}